package com.koron.css2.meterService.impl;

import com.github.pagehelper.PageInfo;
import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.mapper.MeterBoreMapper;
import com.koron.css2.baseConfig.queryBean.MeterBoreQueryBean;
import com.koron.css2.baseConfig.vo.MeterBoreVO;
import com.koron.css2.common.utils.DateUtils;
import com.koron.css2.meterService.bean.query.MsChgPlanDetailQueryBean;
import com.koron.css2.meterService.dto.MsChgPlanDetailDto;
import com.koron.css2.meterService.mapper.MsChgPlanDetailMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 拆表详情查询
 * @author 周利斌
 *
 */
public class MsChgQuery implements ServerInterface{

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		@SuppressWarnings("rawtypes")
		MessageBean<PageInfo> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", PageInfo.class);
		try {
			MsChgPlanDetailQueryBean query = JsonUtils.objectToPojo(req.getData(), MsChgPlanDetailQueryBean.class);
			MsChgPlanDetailMapper mapper = factory.getMapper(MsChgPlanDetailMapper.class);
			MeterBoreMapper meterBoreMapper = factory.getMapper(MeterBoreMapper.class);
			List<MsChgPlanDetailDto> data = mapper.selectListForCB(query);
			List<MeterBoreVO> meterBores = meterBoreMapper.selectMeterBoreList(new MeterBoreQueryBean());
			Map<String, String> meterForms = Tools.mapDicByCode(factory, "MMF"); //水表形态
			Map<String, String> handleWays = Tools.mapDicByCode(factory, "OMD"); //换表类型
			for(MsChgPlanDetailDto t : data) {
				MeterBoreVO meterBore = meterBores.stream().filter(k -> Objects.equals(t.getOldMeterBore(), k.getId())).findFirst().orElse(new MeterBoreVO());
				t.setOldMeterBore(meterBore.getBoreName());
				/*if(Objects.equals("1", t.getMeterForm())) {
					t.setTerm(meterBore.getNewChangeCycle());
				}
				if(Objects.equals("2", t.getMeterForm())) {
					t.setTerm(meterBore.getOldChangeCycle());
				}*/
				if(t.getSetupMeterDate() != null) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					t.setUsedTerm(DateUtils.betweenMonths(sdf.parse(t.getSetupMeterDate()), new Date()));
				}
				t.setMeterForm(meterForms.get(t.getMeterForm()));
				t.setOldHandleWayName(handleWays.get(t.getOldHandleWay()));
			}
			info.setData(new PageInfo<MsChgPlanDetailDto>(data));
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription("查询失败");
			logger.error(e.getMessage(), e);
		}
		return info;
	}

}
